package com.cgw.auth.config;

import com.cgw.auth.Interceptor.AuthInterceptor;
import com.cgw.auth.attribute.AuthApiAttribute;
import com.cgw.auth.service.AuthorizeInfoService;
import lombok.RequiredArgsConstructor;
import org.redis.service.RedisService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * InitAuthBean
 *
 * @author grl
 * @date 2024/4/28
 */

@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(value = "authority.enable", havingValue = "true",matchIfMissing = true)
public class InitAuthInterceptor implements WebMvcConfigurer {

    private final RedisService redisService;
    private final AuthApiAttribute authApiAttribute;
    private final AuthorizeInfoService authorizeInfoService;

    /**
     * 配置拦截器
     * @param registry 相当于拦截器的注册中心
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //下面这句代码相当于添加一个拦截器   添加的拦截器就是我们刚刚创建的
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(
                new AuthInterceptor(authApiAttribute,redisService,authorizeInfoService))
                //addPathPatterns()配置我们要拦截哪些路径 addPathPatterns("/**")表示拦截所有请求，包括我们的静态资源
                .addPathPatterns(authApiAttribute.getIncludePath());
        //excludePathPatterns()表示我们要放行哪些（表示不用经过拦截器）
        // excludePathPatterns("/","/login")表示放行“/”与“/login”请求
        //如果有静态资源的时候可以在这个地方放行
        List<String> excludePath = authApiAttribute.getExcludePath();
        if(excludePath != null && !excludePath.isEmpty()){
            interceptorRegistration.excludePathPatterns(excludePath);
        }
    }
}
